import axios from 'axios'
import store from '@/store'
import qs from 'qs'
import { setToken, getToken, canTurnTo } from '@/libs/util'

// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  const { statusText, status, request: { responseURL } } = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
	var token = getToken();
	// if (token && token != undefined && token != 'undefined') {
	// 	try {
	// 		getToken = JSON.parse(token);
	// 		token 	 = getToken.token;
	// 	} catch(e) {
	// 		token 	 = '';
	// 	}
	// }
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'Content-Type' 	: 'application/x-www-form-urlencoded;charset=utf-8',
		'Authorization' : 'Bearer '+ token 
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data, status } = res
      return { data, status }
    }, error => {
      this.destroy(url)
      addErrorLog(error.response)
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options);
    this.interceptors(instance, options.url)
    return instance(options)
  }
  access (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options);
    let contentType = options.headers['Content-Type'];
    if(contentType && contentType.indexOf('www-form') > -1) {
      if (options.method == 'get') {
        options.params = qs.parse(options.params);
      } else {
        options.data   = qs.stringify(options.data);
      }
    } else if(contentType && contentType.indexOf('multipart/form-data') > -1) {
      options.headers = {
        'Content-Type': 'multipart/form-data'
      }
      //options.data   = qs.stringify(options.data);
      // if (options.method == 'get') {
      //   options.params   = qs.parse(options.params);
      // } else {
      //   options.data   = qs.parse(options.data);
      // }
    }
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
